<%@page import="com.glowdayz.common.PatternChecker"%>
<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@page import="com.glowdayz.common.DBHandler"%>
<%@page import="com.glowdayz.common.ApiHandler"%>
<%@page import="com.glowdayz.common.ApiHandler.XmlData"%>
<%@page import="com.glowdayz.glowmee.cmd.RegisterCMD"%>
<%@page import="com.glowdayz.glowmee.dao.RegisterDAO"%>
<%@page import="java.util.ArrayList"%>
<%
	DBHandler.getInstance().connect();

	ApiHandler web = new ApiHandler(request, out, "JSPglowmee");
	
	PatternChecker checker = PatternChecker.getInstance();
	String nickName = web.getValue("nickName");
	String eMail = web.getValue("eMail");
	String password = web.getValue("password");
	String regId = web.getValue("regId");
	String recommenderText = web.getValue("recommender");
	
	if (!checker.isValue(nickName) || !checker.isValue(eMail) ||!checker.isValue(password)) {
		DBHandler.getInstance().disconnect();
		web.result(null, "닉네임이나 이메일 또는 비밀번호값이 없습니다.");
		return;
	}
	
	int count = DBHandler.getInstance().getCount("register", "idRegister", "nickName='" + nickName + "'");
	if (count > 0) {
		DBHandler.getInstance().disconnect();
		web.result(null, "해당 닉네임은 이미 사용중입니다.");
		return;
	}
	count = DBHandler.getInstance().getCount("register", "idRegister", "eMail='" + eMail + "'");
	if (count > 0) {
		DBHandler.getInstance().disconnect();
		web.result(null, "해당 이메일은 이미 사용중입니다.");
		return;
	}
	
	int insert = 0;
	
	if (recommenderText.equals("")) {
		RegisterCMD cmd = new RegisterCMD(eMail, password, -1, nickName, regId);
		insert = RegisterDAO.getInstance().insertRegister(cmd);
	} else {
		int recommenderCount = DBHandler.getInstance().getCount("register", "idRegister", "nickName='" + recommenderText + "'");
		if (recommenderCount < 1) {
			DBHandler.getInstance().disconnect();
			web.result(null, "해당 추천인이 존재하지 않습니다.");
			return;
		}
		int recommender = RegisterDAO.getInstance().getRecommender(recommenderText);
		RegisterCMD cmd = new RegisterCMD(eMail, password, recommender, nickName, regId);
		insert = RegisterDAO.getInstance().insertRegister(cmd);
	}
	
	if (insert < 1) {
		DBHandler.getInstance().disconnect();
		web.result(null, "추가에 실패하였습니다.");
		return;
	}
	
	DBHandler.getInstance().disconnect();
	
	ArrayList<XmlData> list = new ArrayList<XmlData>();
	list.add(new XmlData("seq", insert));
	list.add(new XmlData("eMail", eMail));
	web.result("SUCCESS", "가입이 완료되었습니다.", list);
%>